

#import "PUCollcetListVC.h"
#import "PUCollcetListCell.h"
#import "PUModel.h"
#import "PUFoodDetailsVC.h"
@interface PUCollcetListVC ()<UITableViewDelegate,UITableViewDataSource,FoodCollcetListCellDelegate>

@property (nonatomic,retain)NSMutableArray *dizhiData;
@property (nonatomic,retain)UITableView *tableView;
@property (nonatomic, copy) void(^listScrollViewDidScroll)(UIScrollView *scrollView);

@end

@implementation PUCollcetListVC


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
//    self.view.backgroundColor=[UIColor colorWithHex:0xF3F3F3];
    self.view.backgroundColor=[UIColor clearColor];
    self.dizhiData=[NSMutableArray array];
    
    
    _tableView = [[UITableView alloc] init];
//    _tableView.backgroundColor=[UIColor colorWithHex:0xF3F3F3];
    _tableView.backgroundColor=[UIColor clearColor];
    //解决scrollToRowAtIndexPath：滚动位置偏差问题
    _tableView.estimatedRowHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    _tableView.estimatedSectionHeaderHeight = 0;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//设置分隔线样式
    _tableView.bounces = YES;
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [self.view addSubview:self.tableView];
//    self.edgesForExtendedLayout = UIRectEdgeTop;
//    _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(0);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];
    
    self.tableView.emptyDataSetSource = self.tableView;
    self.tableView.emptyDataSetDelegate= self.tableView;
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadData];
    }];
    
//    self.tableView.mj_footer=[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        [weakSelf loadMoreRecommendData];
//    }];
    
    self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = iPhoneXs ? 34 : 0;
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer.hidden = YES;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"foodCollcetNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"loginSuccessUpdataNotification" object:nil];//登录成功---刷新列表
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"showLoginNotification" object:nil];//退出登录成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"historyNotification" object:nil];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 96*KWidthScale;
//    FLMyTaoHuaCell *cell = (FLMyTaoHuaCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
//    return cell.rowHeight;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dizhiData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

//    FLModel *model=self.dizhiData[indexPath.row];
    PUFoodModel *model=self.dizhiData[indexPath.row];
    static NSString *cellIdentifier1 = @"FoodCollcetListCell";//定义一个可重用标识
    PUCollcetListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];//从重用队列里获取可重用的cell
    if (cell==nil)
    {
        //如果不存在，创建一个可重用cell
        cell =[[PUCollcetListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier1] ;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.backgroundColor=[UIColor clearColor];
    [cell setFoodModel:model type:self.type];
    cell.delegate=self;
    return cell;
    
}

-(void)clickBtn:(PUCollcetListCell *)cell{

    PUModel *model=cell.model;
    
    NSMutableArray *data=[NSMutableArray array];
    //创建一个归档文件夹
    NSArray *library = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *strLib = [[library objectAtIndex:0] stringByAppendingPathComponent:@"archive"];
    BOOL directory = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:strLib isDirectory:&directory])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:strLib withIntermediateDirectories:NO attributes:nil error:nil];
    }
    //归档
    NSString *entityArchive = [strLib stringByAppendingPathComponent:[NSString stringWithFormat:@"shangjiaDataArchive%@",[Config getID]]];
//    [NSKeyedArchiver archiveRootObject:data toFile:entityArchive];
    //数据源从归档中读出
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
    NSLog(@"%@",array);
    for (int i=0; i<array.count; i++) {
        NSDictionary *dic=array[i];
        if ([dic[@"flowers_buyTime"] isEqualToString:model.flowers_buyTime]) {
            [array removeObjectAtIndex:i];
        }
    }
    [NSKeyedArchiver archiveRootObject:array toFile:entityArchive];
    
    [self.dizhiData removeObject:model];
    [self addEmptyData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PUFoodModel *model=self.dizhiData[indexPath.row];
    PUFoodDetailsVC *vc=[[PUFoodDetailsVC alloc]init];
    vc.model=model;
//    [vc setCollectBlock:^{
//        [collectionView reloadItemsAtIndexPaths:@[indexPath]];
//    }];
    [self.navigationController pushViewController:vc animated:YES];
 
}
/**
 响应链的方法
 */
- (UIViewController *)viewController {
    for (UIView* next = [self.view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}
-(void)loadData{
    [self loadArchiveData];
    [self addEmptyData];
   
}

//加载归档的数据
-(void)loadArchiveData{
    NSMutableArray *data=[NSMutableArray array];
    NSString *library=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    NSString *strLib = [library stringByAppendingPathComponent:@"archive"];
    BOOL directory = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:strLib isDirectory:&directory]){
        [[NSFileManager defaultManager] createDirectoryAtPath:strLib withIntermediateDirectories:NO attributes:nil error:nil];
    }
    
    NSString *str=[NSString stringWithFormat:@"collectDataArchive%@",[Config getID]];
    if (self.type==1) {
        str=[NSString stringWithFormat:@"historyDataArchive%@",[Config getID]];
    }
    //从归档中读出
    NSString *arrayArchive =[strLib stringByAppendingPathComponent:str];//用首页唯一标示id创建文件名
    NSArray *categoryAry = [NSKeyedUnarchiver unarchiveObjectWithFile:arrayArchive];
    if (categoryAry&&[categoryAry count])
    {
        data=[NSMutableArray arrayWithArray:categoryAry];
        NSLog(@"%@",data);
    }
    NSMutableArray *array=[NSMutableArray array];
    for (NSDictionary *dic in data) {
        for (PUFoodsModel *model in PUFoodsModels.shared.list) {
           
            for (PUFoodModel *model2 in model.foods) {
                
                if ([dic[@"name"] isEqualToString:model2.name]) {
                    model2.time=dic[@"time"];
                    [array addObject:model2];
                }
            }
        }
    }
    self.dizhiData=array;
    NSLog(@"%@",array);
}


-(void)addEmptyData{
    [self.tableView.mj_header endRefreshing];
    self.tableView.configuer.emptyType =  ( self.dizhiData.count == 0) ? DznEmptyDataTypeSuccess : DznEmptyDataTypeDefault;
    //        self.tableView.configuer.emptyType =  DznEmptyDataTypeSuccess;
    [self.tableView reloadData];
}

-(void)showSVProgressHUDStr:(NSString *)str{
    if ([str isKindOfClass:[NSNull class]]||str==nil||[str isEqualToString:@""]) {
        return;
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:str];
}

#pragma mark - GKPageListViewDelegate
- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.tableView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView * _Nonnull))callback {
    self.listScrollViewDidScroll = callback;
}

@end

